package com.bw.controller.dc;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.dc.PiProcess;
import com.bw.resp.ResponseResult;
import com.bw.service.dc.IPiProcessService;
import com.bw.utils.ExportExcel;
import com.bw.utils.ReadExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yzz
 * @since 2020-06-17
 */
@RestController
@RequestMapping("/pro")
public class PiProcessController {
    @Autowired
    private IPiProcessService iPiProcessService;
    //定义日志工具
    private final Logger logger= LoggerFactory.getLogger(PiProcessController.class);
    /**
     * 查询原材料列表
     */
    @PostMapping("/list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody PiProcess piProcess) {
        logger.info("工序查询开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.ne("dstatus",1);//排除已经删除的数据
            if(piProcess.getName()!=null){//根据名称查询
                qw.like("name","%"+piProcess.getName()+"%");
            }
            PageHelper.startPage(page,size);//开启分页
            List plist = iPiProcessService.list(qw);//查询list
            PageInfo pageInfo = new PageInfo(plist);//分页后数据
            re.setResult(pageInfo);//存储
            logger.info("工序查询结束");
            return re;
        } catch (Exception e) {
            logger.error("工序查询异常，{}",e.toString());
            return re;
        }
    }

    /**
     * 添加工序
     * @param piProcess
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save( @RequestBody PiProcess piProcess) {
        logger.info("工序添加开始");
        ResponseResult re = new ResponseResult(false, 400, "操作失败");
        try {
            if(piProcess!=null){//不为空时添加
                piProcess.setDstatus(0);//默认未删除
                if(piProcess.getId()!=null){
                    iPiProcessService.saveOrUpdate(piProcess);
                    re.setMessage("修改成功");
                }else{
                    iPiProcessService.save(piProcess);
                    re.setMessage("添加成功");
                }
            }
            re.setSuccess(true);
            logger.info("工序添加结束");
            return re;
        } catch (Exception e) {
            logger.error("工序添加异常，{}",e.toString());
            return re;
        }
    }

    /**
     * 根据id回显
     * @param id
     * @return
     */
    @PostMapping("/getById/{id}")
    public ResponseResult getById(@PathVariable("id") Long id) {
        logger.info("工序回显开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            PiProcess byId = iPiProcessService.getById(id);
            re.setSuccess(true);
            re.setMessage("查询成功");
            re.setCode(200);
            re.setResult(byId);//存储
            logger.info("工序回显结束");
            return re;
        } catch (Exception e) {
            logger.error("工序回显异常，{}",e.toString());
            return re;
        }
    }
    /**
     * 根据id删除材料(需要逻辑删除)
     *
     * @param id
     * @return
     */
    @PostMapping("/delById/{id}")
    public ResponseResult delById(@PathVariable("id") Long id) {
        logger.info("工序删除开始");
        ResponseResult re = new ResponseResult(false, 400, "删除失败");
        try {
            //查找对应工序
            PiProcess byId = iPiProcessService.getById(id);
            byId.setDstatus(1);//修改删除状态为1，已删除
            iPiProcessService.saveOrUpdate(byId);//保存
            re.setSuccess(true);
            re.setMessage("删除成功");
            logger.info("工序删除结束");
            return re;
        } catch (Exception e) {
            logger.error("工序文删除异常，{}",e.toString());
            return re;
        }
    }
    /**
     * 文件导入
     *
     * @param file
     * @return “提示信息”
     */
    @PostMapping("/imporExcel")
    public ResponseResult imporExcel(MultipartFile file) {
        logger.info("工序文件导入开始");
        ResponseResult re = new ResponseResult(false, 400, "上传失败");
        try {
            //获取后缀
            String hou = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'), file.getOriginalFilename().length());
            InputStream in = file.getInputStream();
            //调用封装工具类，处理数据
            List<Map> readExcel = ReadExcel.readExcel(hou, in);
            String jsonString = JSON.toJSONString(readExcel);//转成string
            List<PiProcess> plist = JSON.parseArray(jsonString, PiProcess.class);//转成对象集合
            //保存
            iPiProcessService.saveBatch(plist);
            re.setSuccess(true);
            re.setMessage("上传成功");
            logger.info("工序文件导入结束");
            return re;
        } catch (Exception e) {
            logger.error("工序文件导入异常，{}",e.toString());
            return re;
        }
    }
    /**
     * 文件导出
     * @param response
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        logger.info("工序文件导出开始");
        QueryWrapper qw = new QueryWrapper();
        qw.ne("dstatus",1);//排除已经删除的数据
        List mlist = iPiProcessService.list(qw);//查询list
        try {
         //   ExportExcel.exportExcel(response,mlist,"测试原材料导出");//调用工具类导出数据
            ExportExcel.exportExcel(response,mlist,"测试工序导出","xls/process.xls");//调用工具类导出数据
            logger.info("工序文件导出结束");
        } catch (Exception e) {
            logger.error("工序文件导出异常，{}",e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 查询原材料列表
     */
    @PostMapping("/getPro")
    public ResponseResult getPro() {
        logger.info("工序查询2开始");
        ResponseResult re = new ResponseResult(false, 400, "查询失败");
        try {
            List plist = iPiProcessService.list();//查询list
            re.setResult(plist);//存储
            re.setSuccess(true);
            re.setMessage("查询成功");
            logger.info("工序查询2结束");
            return re;
        } catch (Exception e) {
            logger.error("工序查询2失败,{}",e.toString());
            return re;
        }
    }
}
